import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    cartList: []
  },
  mutations: {
    addCounter(state, payload) {
      payload.count++
    },
    addCart(state,payload) {
      state.cartList.push(payload)
    }
  },
  actions: {
    addCart({state,  commit}, payload) {
      return new Promise((resolve) => {
        let oldProduct = state.cartList.find(item => item.iid === payload.iid)
        if(oldProduct) {
          commit('addCounter', oldProduct)
          resolve('当前数量加1')
        } else {
          payload.count = 1
          payload.checked = true
          commit('addCart', payload)
          resolve('添加了新的商品')
        }
      })
    }
  },
  getters: {
    cartLength(state) {
      return state.cartList.length
    },
    cartList(state) {
      return state.cartList
    }
  }
})

export default store
